package uiTest;

import javax.swing.*;
import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

public class PanelTableEditorTest extends JFrame {

    private JTable table;

    public PanelTableEditorTest() {
        this.setLayout(new BorderLayout());
        table = new JTable(10, 10);
        table.getSelectionModel().setSelectionMode(
            ListSelectionModel.SINGLE_SELECTION);
        table.setCellSelectionEnabled(true);
        table.setDefaultEditor(Object.class, new SimpleMultiRowCellEditor());
        table.setSurrendersFocusOnKeystroke(true);
        table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
            .put(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F2, 0),
            "none");
        table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
            .put(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ENTER, 0),
            "startEditing");
        this.add(table.getTableHeader(), BorderLayout.NORTH);
        this.add(table, BorderLayout.CENTER);
        pack();
        setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            public void run() {
                new PanelTableEditorTest();
            }
        });
    }

    public class SimpleMultiRowCellEditor extends DefaultCellEditor {

        final JPanel panel;
        private final JButton rowCount;

        public SimpleMultiRowCellEditor() {
            super(new JTextField());
            this.setClickCountToStart(1);

            rowCount = new JButton();
            rowCount.setVisible(true);
            panel = new JPanel();
            panel.setSize(300, 100);
            panel.setBackground(Color.RED);
            panel.setOpaque(false);
            panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
            panel.add(rowCount);
            panel.add(editorComponent);
            panel.addFocusListener(new PanelFocusListener());
        }

        public Component getTableCellEditorComponent(
            final JTable table,final Object val, final boolean isSelected,
            final int row, final int column) {
            rowCount.setText("1");
            delegate.setValue(val);
            editorComponent.requestFocusInWindow();
            return panel;
        }

        class PanelFocusListener implements FocusListener {

            public void focusGained(FocusEvent e) {
                editorComponent.requestFocusInWindow();
            }

            public void focusLost(FocusEvent e) {
            }
        }
    }
}
